package org.go.ee.jmx.mbean.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadInfo;
import java.util.HashMap;
import java.util.Map;

public class JVM5Monitor implements JVM5MonitorMBean {

	@Override
	public Map getThreadInfo() throws Exception {
		Map map = new HashMap();
		long[] threadIds = ManagementFactory.getThreadMXBean().getAllThreadIds();
		ThreadInfo[] objThreadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadIds, 2147483647);
		for (int i = 0; i < objThreadInfo.length; ++i) {
			map.put(objThreadInfo[i].getThreadName(), objThreadInfo[i].getThreadState().name());
		}
		return map;
	}

	@Override
	public String getAllThreadInfo() throws Exception {
		long[] threadIds = ManagementFactory.getThreadMXBean().getAllThreadIds();
		ThreadInfo[] objThreadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadIds, 2147483647);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < objThreadInfo.length; ++i) {
			sb.append("<data>");
			sb.append("<rownum>" + (i + 1) + "</rownum>");
			sb.append("<id>" + objThreadInfo[i].getThreadId() + "</id>");
			sb.append("<state>" + objThreadInfo[i].getThreadState().name() + "</state>");
			sb.append("<name><![CDATA[" + objThreadInfo[i].getThreadName() + "]]></name>");
			StackTraceElement[] stack = objThreadInfo[i].getStackTrace();
			StringBuffer tmp = new StringBuffer();
			for (int j = 0; j < stack.length; ++j) {
				tmp.append(stack[j].getClassName() + "." + stack[j].getMethodName() + "(" + stack[j].getFileName() + ":" + stack[j].getLineNumber() + ")\n");
			}
			sb.append("<stack><![CDATA[" + tmp + "]]></stack>");
			sb.append("</data>");
		}
		return sb.toString();
	}

	@Override
	public String getMemoryInfo() throws Exception {
		MemoryUsage objMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
		long total = objMemoryUsage.getMax();
		long used = objMemoryUsage.getUsed();
		StringBuffer sb = new StringBuffer();
		sb.append("<data>");
		sb.append("<t>" + total + "</t>");
		sb.append("<u>" + used + "</u>");
		sb.append("</data>");
		return sb.toString();
	}

}
